package org.geometerplus.fbreader.formats;

import android.text.TextUtils;

import com.example.administrator.fangbook.appliction.HtlApplication;
import com.example.administrator.fangbook.dataLibrary.book.ShelfItemBook;
import com.example.administrator.fangbook.read.bean.Chapter;
import com.example.administrator.fangbook.read.library.constants.GlobalConstants;
import com.example.administrator.fangbook.utils.FileUtils;

import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.fbreader.formats.m17k.ChapterPayUtil;
import org.geometerplus.zlibrary.core.filesystem.ZL17KPlainTxtFile;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.filesystem.ZLTxtFile;
import org.geometerplus.zlibrary.text.model.ZLTextModel;
import org.geometerplus.zlibrary.text.view.ZLTextPosition;

import java.util.concurrent.CopyOnWriteArrayList;

public abstract class BasicChapterReader extends BookReader {
    /**
     * 阅读章节id
     */
    protected int myReadingChapterId = -Integer.MAX_VALUE;
    /**
     * 上一章阅读id
     */
    protected String myPreReadingChapterId = null;

    /**
     * 章节列表（并发安全）
     */
    protected final CopyOnWriteArrayList<Chapter> myChapters = new CopyOnWriteArrayList<Chapter>();

    /**
     * 打开自动预加载
     */
    protected boolean myIsOpenAutoPreload = true;

    /**
     * 书的id和名称
     */
    protected String myBookId;
    protected String myBookName;


    protected BasicChapterReader(FBReaderApp app, ZLFile file) {
        super(app, file);
    }

    protected void init(ZLFile file) {
        myBookId = myReadingBook.getBookId();
        myBookName = myReadingBook.getName();
    }

    protected abstract ZLFile createZLFile(String bookId, String bookName, String chapterId, String chapterName);


    /**
     * 判断是否包含下一章内容
     *
     * @return
     */
    public boolean hasNextChapter() {
        synchronized (myChapters) {
            //当前章节是否在章节列表的长度范围
            return myReadingChapterId >= 0 && myReadingChapterId < myChapters.size() - 1;
        }
    }

    /**
     * 是否存在章能缓存的章节
     *
     * @return
     */
    public boolean hasNextCacheChapter() {
        synchronized (myChapters) {
            return myReadingChapterId >= 0 && myReadingChapterId < myChapters.size() - 2;
        }
    }

    /**
     * 判断上章是否存在
     *
     * @return
     */
    public boolean hasPreviousChapter() {
        synchronized (myChapters) {
            return myReadingChapterId > 0 && myChapters.size() > 0 && myReadingChapterId < myChapters.size();
        }
    }

    /**
     * 得到下章内容
     *
     * @return
     */
    public Chapter getNextChapter() {
        synchronized (myChapters) {
            Chapter chapter = null;
            if (hasNextChapter()) {
                chapter = myChapters.get(myReadingChapterId + 1);
            }
            if (chapter != null && TextUtils.isEmpty(chapter.getBookId())) {
                //如果章节不为null，但是章节id为null，传入书籍id
                chapter.setBookId(getBookId());
            }
            return chapter;
        }
    }

    /**
     * 得到上一章内容
     *
     * @return
     */
    public Chapter getPreviousChapter() {
        synchronized (myChapters) {
            Chapter chapter = null;
            if (hasPreviousChapter()) {
                chapter = myChapters.get(myReadingChapterId - 1);
            }
            if (chapter != null && TextUtils.isEmpty(chapter.getBookId())) {
                chapter.setBookId(getBookId());
            }
            return chapter;
        }
    }

    /**
     * 得到第一章的内容
     *
     * @return
     */
    public Chapter getFirstChapter() {
        synchronized (myChapters) {
            Chapter chapter = null;
            if (!myChapters.isEmpty()) {
                chapter = myChapters.get(0);
            }
            return chapter;
        }
    }

    /**
     * 通过章节id获取章节对象，并将阅读游标置为该章节（转到指定id的章节）
     * 如果传入的章节id为null，则返回第一章的内容
     *
     * @param chapterId 章节id
     * @return Chapter
     */
    public Chapter gotoChapterById(String chapterId) {
        synchronized (myChapters) {
            Chapter chapter = null;
            if (!TextUtils.isEmpty(chapterId)) {
                int i = 0;
                for (Chapter c : myChapters) {
                    if (c != null && !TextUtils.isEmpty(c.getId()) && TextUtils.equals(chapterId, c.getId())) {
                        myReadingChapterId = i;
                        chapter = c;
                        break;
                    }
                    i++;
                }
            } else {
                if (!myChapters.isEmpty()) {
                    chapter = myChapters.get(0);
                    myReadingChapterId = 0;
                }
            }
            if (chapter != null && TextUtils.isEmpty(chapter.getBookId())) {
                chapter.setBookId(getBookId());
            }
            if (chapter != null) {
                //判断章节是否下载
                if (ChapterPayUtil.isDownload(null, chapter.getBookId(), chapter)) {
                    myPreReadingChapterId = chapter.getId();
                }
            }
            return chapter;
        }
    }

    /**
     * 4.1.2 huangyx, 为了解决阅读时，各种有网无网切换试问章节标题问题
     * 转到末尾章节（字面意思）
     * 内容中是拿了上一章的章节id获取上一张的内容，调取view刷新
     *
     * @return 末尾章节内容
     */
    public Chapter gotoLastChatper() {
        if (!TextUtils.isEmpty(myPreReadingChapterId)) {
            Chapter chapter = gotoChapterById(myPreReadingChapterId);
            if (chapter != null) {
//                FBReaderApp reader = (FBReaderApp) FBReaderApp.Instance();
                myApplication.getViewWidget().repaintForcely();
            }
            return chapter;
        }
        return null;
    }

    /**
     * 获取当前阅读的章节
     */
    public Chapter getReadingChapter() {
        synchronized (myChapters) {
            Chapter chapter = null;
            if (myChapters != null && myReadingChapterId >= 0 && myReadingChapterId < myChapters.size()) {
                chapter = myChapters.get(myReadingChapterId);
            }
            if (chapter != null && TextUtils.isEmpty(chapter.getBookId())) {
                chapter.setBookId(getBookId());
            }
            return chapter;
        }
    }


    public abstract void gotoChapter(final Chapter chapter, ZLTextPosition position);

    /**
     * 根据文件和位置跳转章节
     *
     * @param zfile
     * @param position
     */
    public void gotoChapter(final ZLFile zfile, final ZLTextPosition position) {
        //根据file文件构建chapter内容
        final Chapter chapter = Chapter.buildChapterByZLFile(zfile);
        myBookId = chapter.getBookId();
        //根据文件获取文件模式
        ZLTextModel model = getModelByFile(zfile);
        if (model != null && model.isLoaded() && model.getId().equals(zfile.getPath())) {
            loadChapterSuccess(model, position, zfile, chapter);
        } else {
            runOnBackground(new Runnable() {
                @Override
                public void run() {
                    readModelData(zfile, !isInstanceOf(zfile), chapter, new OnBookReaderListener() {
                        @Override
                        public void onLoadedSuccess(ZLFile file, ZLTextModel model) {
                            loadChapterSuccess(model, position, zfile, chapter);
                        }
                    });
                }
            }, true);
        }
    }

    /**
     * 加载章节成功
     *
     * @param model    当前model
     * @param position 章节位置
     * @param zfile    章节文件
     * @param chapter  章节
     */
    private void loadChapterSuccess(ZLTextModel model, ZLTextPosition position, ZLFile zfile, Chapter chapter) {
        if (position != null) {
            zfile.setStartPositioin(position);
        }
        myAnimationManager.setModel(zfile, model);
        readChapterSuccess(chapter);
    }

    /**
     * 成功加载阅读某章节后调用
     *
     * @param chapter Chapter
     */
    public void readChapterSuccess(Chapter chapter) {

    }


    /**
     * 从缓存中获取当前文件的textModel
     *
     * @param file
     * @return
     */
    protected ZLTextModel getModelByFile(ZLFile file) {
        ZLTextModel model = null;
        synchronized (this) {
            if (myCachedModelData != null && file != null) {
                model = myCachedModelData.get(file);
            }
        }
        return model;
    }

    /**
     * 跳转上一章
     *
     * @param toFirstPage 是否到第一页
     */
    public void gotoPreChapter(final boolean toFirstPage) {
        gotoPreChapter(getPreviousChapter(), toFirstPage);
    }

    /**
     * 到上一章
     *
     * @param toFirstPage 是否到第一页
     * @param showLoading 是否显示loading
     */
    public void gotoPreChapter(final boolean toFirstPage, boolean showLoading) {
        gotoPreChapter(getPreviousChapter(), toFirstPage, showLoading);
    }

    /**
     * 到上一章
     *
     * @param previousChapter
     * @param toFirstPage
     */
    protected void gotoPreChapter(final Chapter previousChapter, final boolean toFirstPage) {
        gotoPreChapter(previousChapter, toFirstPage, false);
    }

    /**
     * 底层加载章节 加载前一章
     *
     * @param previousChapter 章节内容
     * @param toFirstPage     是否到第一页
     * @param showLoading     是否显示加载框
     */
    protected void gotoPreChapter(final Chapter previousChapter, final boolean toFirstPage, boolean showLoading) {
        if (previousChapter == null) {
            return;
        }
        //得到上一章的file文件
        final ZLFile file = createZLFile(myBookId, myBookName, previousChapter.getId(), previousChapter.getName());
        //根据file得到文件模式
        ZLTextModel model = getModelByFile(file);

        if (model != null && model.isLoaded() && model.getId().equals(file.getPath())) {
            myAnimationManager.setPrevModelData(previousChapter, model, toFirstPage);
            readChapterSuccess(previousChapter);
        } else {
            runOnBackground(new Runnable() {
                @Override
                public void run() {
                    readModelData(file, !isInstanceOf(file), previousChapter, new OnBookReaderListener() {
                        @Override
                        public void onLoadedSuccess(ZLFile file, ZLTextModel model) {
                            myAnimationManager.setPrevModelData(previousChapter, model, toFirstPage);
                            readChapterSuccess(previousChapter);
                        }
                    });
                }
            }, true);
        }
    }

    /**
     * 到下一章
     */
    public void gotoNextChapter() {
        gotoNextChapter(getNextChapter());
    }

    /**
     * 到下一章
     *
     * @param showLoading 是否显示加载
     */
    public void gotoNextChapter(boolean showLoading) {
        gotoNextChapter(getNextChapter(), showLoading);
    }

    /**
     * 到下一章
     *
     * @param nextChapter 下一章内容
     */
    protected void gotoNextChapter(final Chapter nextChapter) {
        gotoNextChapter(nextChapter, false);
    }

    /**
     * 判断传入文件是否是ZLTxtFile
     *
     * @param file
     * @return
     */
    private boolean isInstanceOf(ZLFile file) {
        return file instanceof ZLTxtFile;
    }

    /**
     * 加载下一章，调用底层
     *
     * @param nextChapter
     * @param showLoading
     */
    protected void gotoNextChapter(final Chapter nextChapter, boolean showLoading) {
        if (nextChapter == null) {
            return;
        }
        final ZLFile file = createZLFile(myBookId, myBookName, nextChapter.getId(), nextChapter.getName());
        ZLTextModel model = null;
        model = getModelByFile(file);
        if (model != null && model.isLoaded() && model.getId().equals(file.getPath())) {
            myAnimationManager.setNextModelData(nextChapter, model);
            readChapterSuccess(nextChapter);
        } else {
            runOnBackground(new Runnable() {
                @Override
                public void run() {
                    readModelData(file, !isInstanceOf(file), nextChapter, new OnBookReaderListener() {
                        @Override
                        public void onLoadedSuccess(ZLFile file, ZLTextModel model) {
                            myAnimationManager.setNextModelData(nextChapter, model);
                            readChapterSuccess(nextChapter);
                        }
                    });
                }
            }, true);
        }
    }

    /**
     * 阅读模型数据
     *
     * @param file
     * @param chineseAllBook 是否是中文书城的书
     * @param chapter
     * @param listener
     */
    private void readModelData(ZLFile file, boolean chineseAllBook, final Chapter chapter, final OnBookReaderListener listener) {
        if (!file.exists()) {
            if (chineseAllBook) {
                if (Chapter.hasDownload(myBookId, chapter.getId()) && !Chapter.isInBookPath(myBookId, chapter.getId())) {
                    FileUtils.copyAssetsData(HtlApplication.getApplication(),
                            GlobalConstants.ASSET_BOOK_PATH + "/" + myBookId,
                            GlobalConstants.BOOK_PATH + "/" + myBookId, chapter.getId());
                }
            }
        }
        if (file.exists()) {
            if (chineseAllBook) {
                FileUtils.bumpChapterContent(myBookId, chapter.getId());
            }
            readModelData(file, new OnModelDataLoaded() {
                @Override
                public void onLoadedSuccess(ZLFile file, ZLTextModel model) {
                    listener.onLoadedSuccess(file, model);
                }

                @Override
                public void onLoadedFailed(ZLFile file, String errorMsg) {
                    myAnimationManager.loadFailed(file, errorMsg);
                }
            });
        } else {
            myAnimationManager.loadFailed(file, "章节文件丢失！");
        }
    }

    /**
     * 第一章节
     */
    public void doFirstChapter() {

    }

    public void doLastChapter() {

    }


    public synchronized int getChapterCount() {
        return myChapters.size();
    }


    @SuppressWarnings("unused")
    public Chapter getChapterByPercent(int percent) {
        synchronized (myChapters) {
            int id = percent * myChapters.size() / 100;
            Chapter chapter = myChapters.get(id - 1 < 0 ? 0 : id - 1);
            if (chapter != null && TextUtils.isEmpty(chapter.getBookId())) {
                chapter.setBookId(getBookId());
            }
            return chapter;
        }
    }

    @SuppressWarnings("unused")
    public int getReadPercent() {
        synchronized (myChapters) {
            int i = myChapters.size();
            if (i <= 0) {
                return 100;
            }
            return (myReadingChapterId + 1) * 100 / i;
        }
    }

    public int getMyReadingChapterId() {
        return (myReadingChapterId + 1);
    }

    public float getReadPercentF() {
        synchronized (myChapters) {
            int i = myChapters.size();
            if (i <= 1) {
                return 0f;
            }
            return (myReadingChapterId + 1) * 100f / i;
        }
    }

    public String getBookId() {
        return myBookId;
    }


    public abstract void destory();

    public void startAutoPreload() {
        myIsOpenAutoPreload = true;
    }

    public void closeAutoPreload() {
        myIsOpenAutoPreload = false;
    }


    /**
     * 切换章节游标
     *
     * @param turnNext
     */
    public void doShiftChapter(boolean turnNext) {
        Chapter chapter = turnNext ? getNextChapter() : getPreviousChapter();
        if (chapter != null) {
            gotoChapterById(chapter.getId());
        }
    }

}
